package org.metasketch.demo.project.load;

import java.io.File;

import org.metasketch.demo.project.DEMOProject;
import org.metasketch.editor.IProjectLoader;
import org.metasketch.editor.Project;
import org.metasketch.file.IFileLoader;
import org.metasketch.logger.Log;

public class DEMOProjectLoader implements IProjectLoader {

	DEMOProject project = null;

	@Override
	public void loadDirectory(File choice) throws Throwable {

		Log.println("Loading metasketch project directory: "
				+ choice.getAbsolutePath() + "...");
		// System.out.flush();

		if (!choice.isDirectory() || !choice.exists())
			throw new Exception(choice.getAbsolutePath()
					+ " is invalid - not a directory, or doesn't exist !");

		project = new DEMOProject();

		File[] files = choice.listFiles();
		for (int i = 0; i < files.length; i++) {
			File file = files[i];
			if (file.isFile() && file.getName().endsWith(".xmi")) {
				loadModel(file, project);
			} else if (file.isDirectory()
					&& file.getName().endsWith(".diagrams")) {
				loadDiagrams(file, project);
			}
		}

		if (project.getDiagrams() == null || project.getModel() == null)
			throw new Exception(
					"Invalid metasketch project directory. No XMI model file or \".diagrams\"  folder found. ");

		// stich together the objects

		// validate

		// set project to directory

		Log.println("Finished loading metasketch project directory: "
				+ choice.getAbsolutePath() + "...");
		// System.out.flush();

	}

	private void loadDiagrams(File file, DEMOProject project) throws Throwable {
		DEMODiagramLoader.loadDiagrams(file, project);
	}

	private void loadModel(File file, DEMOProject project) throws Throwable {
		DEMOModelLoader.loadModel(file, project);
	}

	@Override
	public Project getProject() {
		return project;
	}

}
